import React from 'react';
import { DnFC } from '@inbiz/react';
import { getMessage } from '@inbiz/react';
import { createBehavior, createResource } from '@inbiz/core';
import TableDesigner from '../../preview/web/index';
import {
  createBaseSchema,
  createComponentLayout,
  createComponentStyleSchema,
  createControllerSchema,
  createDecoratorStyleSchema,
  createInbizSchema,
  createRelationSchema,
  createSoureSchema,
} from '@inbiz/setters';
import * as Schema from './schema';
import { TableStyle, TableViewType } from './schema';
import * as Locale from '../locale';
import {
  ActionEnum,
  ActionPosition,
  Actions,
  ActionTypeMap,
  ActionTypeObj,
  Option,
  SearchConst,
  TmplDefaultConfig,
  TmplDefaultConfig2,
  TmplDefaultConfig3,
  UnitEnum,
} from '../../shared';
import { uuid } from '@inbiz/utils';
import { Field } from '@formily/core';

import MyAutoComplete from '@components/form/base/EformInput/designer/components/MyAutoComplete';
import TableTopQuery from '../../preview/web/TableTopQuery';
import Toolbar from '../../preview/web/Toolbar';
import TableTopBtnGroup from '../../preview/web/TableTopBtnGroup';

const Table: DnFC<React.ComponentProps<typeof TableDesigner>> & {
  Query?: React.ComponentProps<any>;
  BtnGroup?: React.ComponentProps<any>;
  Toolbar?: React.ComponentProps<any>;
} = TableDesigner;

const createSchema = (name: string) => {
  return createInbizSchema({
    attribute: {
      ...TableViewType,
      ...createBaseSchema(Schema[name], undefined, true, {hiddenTitle: true}),
      ...createRelationSchema(
        {
          range: 'current',
          filter: 'Table',
        },
        {
          relationField: {
            type: 'string',
            'x-decorator': 'FormItem',
            'x-component': MyAutoComplete,
            'x-reactions': {
              dependencies: ['form.senior.soure.x-component-props.modelname'],

              fulfill: {
                schema: {
                  'x-component-props.update': '{{$deps[0]}}',
                  'x-component-props.valueType': 'value',
                  'x-component-props.syncModel': `{{$deps[0].value}}`,
                },
              },
            },
          },
        },
      ),
    } as any,
    style: {
      ...createComponentStyleSchema(TableStyle),
      ...createComponentLayout(),
      ...createDecoratorStyleSchema(),
    },
    senior: {
      // ...createModelSchema(),
      ...createSoureSchema({
        isApi: true,
        props: {
          resultKeys: ['Success', 'Rows', 'Total'],
          isPrimaryKey: true,
        },
        fieldChange: (form, value: any) => {
          if (!value?.isChangeModel) {
            return;
          }
          const tableViewType = form.query(/tableViewType$/).take() as Field;
          const sortField = form.query(/sortField$/).take() as Field;
          const cacheModelkey = (form.query(/modelkey$/).take() as Field)
            ?.caches.value;
          if (tableViewType.value != 'table') return;
          const queryFields =
            value?.queryField
              ?.filter((field: any) => !field.IsMany)
              ?.map((item: any) => {
                return {
                  value: item.AnotherName
                    ? item.AnotherName
                    : item.Master
                      ? item.FieldName.split('$')[1]
                      : item.FieldName,
                  label: item.AnotherName
                    ? item.AnotherName
                    : item.Master
                      ? item.FieldName.split('$')[1]
                      : item.FieldName,
                  ModelKey: item.ModelKey,
                  Master: item.Master,
                  origin_FieldName: item.FieldName,
                  sourcetype: 'modal',
                  columnName: item.ColName
                };
              }) || [];
          if (cacheModelkey !== value?.value) {
            sortField.value = undefined;
            sortField.setDataSource(undefined);
          }
          const attrs = queryFields.map((item: any) => {
            return {
              propName: item.value,
              visible: '1',
              width: 100,
              columnName: item.columnName
            };
          });
          const field = form.query(/columnConfig$/).take() as Field;
          if (
            cacheModelkey === value?.value &&
            field.value.tableValues.attrs?.length
          ) {
            // 有值时，保留已配置的
            const newAttrs = attrs.map((item: any) => {
              const attr = field.value.tableValues.attrs.find(
                (fieldItem: any) => item.propName === fieldItem.propName,
              );
              if (attr) {
                return attr;
              }
              return item;
            });
            field.value = {
              ...field.value,
              queryFields,
              tableValues: {
                ...field.value.tableValues,
                attrs: newAttrs,
              },
            };
          } else {
            // 没有的时候设置值
            field.value = {
              ...field.value,
              queryFields,
              tableValues: {
                ...field.value.tableValues,
                attrs,
              },
            };
          }
        },
      }),
    },
    controller: createControllerSchema({
      events: [
      {
        name: "onOpen",
        label: "弹框打开事件",
      },
      {
        name: "onClose",
        label: "弹框关闭事件",
      },
      {
        name: "onAdd",
        label: "数据添加事件",
      },
      {
        name: "onEdit",
        label: "数据修改事件",
      },
      {
        name: "onDelete",
        label: "数据删除事件",
      },
      {
        name: "onSuccess",
        label: "数据请求成功事件",
      },
      {
        name: "onError",
        label: "数据请求失败事件",
      },
      {
        name: "onClick",
        label: "单击事件",
      },
      {
        name: "onDblClickRow",
        label: "双击行事件",
        platform: 'web'
      },
      {
        name: "onSelect",
        label: "选中/取消选中事件",
        platform: 'web'
      },
      {
        name: "onSelectAll",
        label: "全选/取消全选事件",
        platform: 'web'
      },
      {
        name: "onQueryClick",
        label: "查询点击事件",
        platform: 'web'
      },
      {
        name: "onClearClick",
        label: "重置点击事件",
        platform: 'web'
      },
      {
        name: "onBeforeOpen",
        label: "弹框打开前回调事件",
        isConfigEvent: true,
        platform: 'web'
      },
      {
        name: "onBeforeClose",
        label: "弹框关闭前回调事件",
        isConfigEvent: true,
        platform: 'web'
      },
      {
        name: "onBeforeSort",
        label: "行排序前回调事件",
        isConfigEvent: true,
        platform: 'web'
      },
      {
        name: "onParamFormat",
        label: "格式化参数",
        isConfigEvent: true,
      },
      {
        name: "onRequest",
        label: "自定义请求",
        isConfigEvent: true,
      },
      {
        name: "onData",
        label: "格式化数据",
        isConfigEvent: true,
      },
      {
        name: "onExportParamFormat",
        label: "格式化导出参数",
        isConfigEvent: true,
        platform: 'web'
      },
      {
        name: "onColumnsFormat",
        label: "列格式化",
        isConfigEvent: true,
        platform: 'web'
      },
      {
        name: "onOperateFormat",
        label: "操作列格式化",
        isConfigEvent: true,
        platform: 'web'
      },
      {
        name: "onBeforeOperationAsync",
        label: "新增/编辑/删除前执行",
        isConfigEvent: true,
      }]
    })
  });
};

export const defaultTableProps = {
  showLineNumber: true,
  resizeColumnWidth: true,
  autoLoad: true,
  showPage: true,
  pageRefresh: true,
  search: true,
  thumbnail: false,
  searchExpanded: SearchConst.expanded,
  expandedButton: 'hidden',
  searchExpandedSize: SearchConst.all,
  searchButtonSize: 'middle',
  searchButtonPosition: 'right',
  buttonRegion: true,
  buttonPosition: 'left',
  rowSelection: false,
  dragSort: false,
  showPosition: 'right',
  showHeightRule: 'adaption',
  tableViewType: 'table',
  showPageType: 'list',
  size: 'small',
  thumbConfig: {
    formItems: {
      fixedActionColumn: 'right',
      actionColumnWidth: 200,
      tableHeaderBtnShow: 'text',
      inLineBtnShow: 'text',
      toolbarDisplayPosition: 'left',
      pageSize: 30,
      widthUnit: UnitEnum.percentage,
      tmplList: [
        {
          name: '默认模板',
          id: 'default',
          config: TmplDefaultConfig(),
        },
        {
          name: '默认模板2',
          id: 'default2',
          config: TmplDefaultConfig2(),
        },
        {
          name: '默认模板3',
          id: 'default3',
          config: TmplDefaultConfig3(),
        },
      ],
      cardTmpl: {
        name: '默认模板',
        id: 'default',
      },
      width: {
        widowWidth: 45,
        widthSuffix: UnitEnum.percentage,
      },
      maxHeight: {
        windowHeight: 60,
        heightSuffix: UnitEnum.percentage,
      },
      minHeight: {
        windowHeight: 45,
        heightSuffix: UnitEnum.percentage,
      },
      position: 'right',
      authControl: true,
      actionGroups: 200,
      actionPanelWidth: 200,
    },
    tableValues: {
      actions: Actions().reduce((data: any[], action) => {
        if (
          ![ActionEnum.add, ActionEnum.view, ActionEnum.edit].includes(
            action.value as ActionEnum,
          )
        ) {
          return data;
        }
        data.push({
          id: uuid(5, 5),
          actionType: action.value,
          actionName: action.label,
          position:
            action.value === ActionEnum.add
              ? ActionPosition.tableHeader
              : ActionPosition.inline,
          openMode: 'modal',
          windowName: action.label,
        });
        return data;
      }, []),
      attrs: [
        {
          placeKey: 'title',
          placeText: '位置1',
          label: '标题',
          typeValue: 'obj',
          propName: '',
          id: '00420',
        },
        {
          placeKey: 'data1',
          placeText: '位置2',
          label: '数据1',
          typeValue: 'obj',
          propName: '',
          id: '13011',
        },
        {
          placeKey: 'data2',
          placeText: '位置3',
          label: '数据2',
          typeValue: 'obj',
          propName: '',
          id: '14411',
        },
        {
          placeKey: 'data3',
          placeText: '位置4',
          label: '数据3',
          typeValue: 'array',
          propName: '',
          id: '44132',
        },
        {
          placeKey: 'data4',
          placeText: '位置5',
          label: '数据4',
          typeValue: 'obj',
          propName: '',
          id: '42342',
        },
      ],
      subWindow: Option().parentAction.reduce((data: any[], action) => {
        ActionTypeMap[action.value].forEach((type: ActionEnum) => {
          if (type === ActionEnum.custom) {
            return;
          }
          data.push({
            id: uuid(5, 5),
            parentAction: action.value,
            actionType: type,
            actionName: ActionTypeObj()[type].label,
          });
        });
        return data;
      }, []),
    },
  },
  rowHeight: 'middle',
  zebraEffectColor: 'rgba(250,250,250,1)',
  tableHeaderColor: 'rgba(248,248,248, 1)',
  columnConfig: {
    formItems: {
      fixedActionColumn: 'right',
      actionColumnWidth: 200,
      tableHeaderBtnShow: 'text',
      inLineBtnShow: 'text',
      toolbarDisplayPosition: 'left',
      pageSize: 30,
      widthUnit: UnitEnum.percentage,
      tmplList: [
        {
          name: '默认模板',
          id: 'default',
          config: TmplDefaultConfig(),
        },
        {
          name: '默认模板2',
          id: 'default2',
          config: TmplDefaultConfig2(),
        },
        {
          name: '默认模板3',
          id: 'default3',
          config: TmplDefaultConfig3(),
        },
      ],
      cardTmpl: {
        name: '默认模板',
        id: 'default',
      },
      width: {
        widowWidth: 45,
        widthSuffix: UnitEnum.percentage,
      },
      maxHeight: {
        height: 60,
        suffix: UnitEnum.percentage,
      },
      minHeight: {
        height: 45,
        suffix: UnitEnum.percentage,
      },
      position: 'right',
      authControl: true,
      actionGroups: 200,
      actionPanelWidth: 200,
    },
    tableValues: {
      actions: Actions().reduce((data: any[], action) => {
        if (
          ![ActionEnum.add, ActionEnum.view, ActionEnum.edit].includes(
            action.value as ActionEnum,
          )
        ) {
          return data;
        }
        data.push({
          id: uuid(5, 5),
          actionType: action.value,
          actionName: action.label,
          position:
            action.value === ActionEnum.add
              ? ActionPosition.tableHeader
              : ActionPosition.inline,
          openMode: 'modal',
          windowName: action.label,
        });
        return data;
      }, []),
      subWindow: Option().parentAction.reduce((data: any[], action) => {
        ActionTypeMap[action.value].forEach((type: ActionEnum) => {
          if (type === ActionEnum.custom) {
            return;
          }
          data.push({
            id: uuid(5, 5),
            parentAction: action.value,
            actionType: type,
            actionName: ActionTypeObj()[type].label,
          });
        });
        return data;
      }, []),
    },
  },
  topBtnMorePopover: 'fold'
};

export const querySchema = createInbizSchema({
  attribute: {},
  style: {
    ...createComponentStyleSchema({}),
    ...createDecoratorStyleSchema(),
  },
});

export const btnGroupSchema = createInbizSchema({
  attribute: {},
  style: {
    ...createComponentStyleSchema({}),
    ...createDecoratorStyleSchema(),
  },
});
const local = [Locale.Query, Locale.BtnGroup];
const schema = [querySchema, btnGroupSchema];
const TablePlugin = ['Table.Query', 'Table.BtnGroup'].map((item, i) => {
  return {
    extends: ['Field'],
    name: item,
    designerLocales: local[i],
    selector: (node: any) => node?.props['x-component'] === item,
    designerProps: {
      cloneable: false,
      deletable: false,
      draggable: false,
      droppable: true,
      propsSchema: schema[i],
    },
  };
});

Table.Behavior = createBehavior(
  {
    name: 'Table',
    extends: ['Field'],
    selector: (node) => node.props?.['x-component'] === 'Table',
    designerProps: {
      // droppable: true,
      propsSchema: createSchema('Table'),
    },
    designerLocales: Locale.Table,
  },
  ...TablePlugin,
);

Table.Resource = createResource({
  icon: 'Table',
  elements: [
    {
      componentName: 'Field',
      props: {
        type: 'void',
        'x-decorator': 'Container',
        'x-component': 'Table',
        'x-decorator-props': {
          clickable: true,
          style: {
            padding: '20px 20px 20px 20px',
          },
          wrapperWidth: 'auto',
        },
        'x-component-props': defaultTableProps,
      },
      children: [
        {
          componentName: 'Field',
          props: {
            type: 'void',
            title: '查询区域',
            'x-decorator': 'Container',
            'x-decorator-props': {
              clickable: true,
            },
            'x-component': 'Table.Query',
            'x-component-props': {
              style: {
                minHeight: '100px',
                width: '100%',
              },
            },
          },
        },
        {
          componentName: 'Field',
          props: {
            type: 'void',
            title: '按钮组区域',
            'x-decorator': 'Container',
            'x-decorator-props': {
              clickable: true,
              style: {
                width: 'inherit',
              },
            },
            'x-component': 'Table.BtnGroup',
            'x-component-props': {
              style: {
                display: 'flex',
                flexWrap: 'wrap',
                minHeight: '32px',
                width: '100%',
              },
            },
          },
        },
      ],
    },
  ],
});

Table.Query = (props) => {
  return <TableTopQuery {...props} />;
};

Table.BtnGroup = (props) => {
  return <TableTopBtnGroup {...props} />;
};

Table.Toolbar = () => {
  return (
    <div>
      <Toolbar />
    </div>
  );
};

export default Table;
